package com.photovoltaic.auth.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.photovoltaic.auth.entity.OperationLog;
import com.photovoltaic.auth.service.OperationLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/auth/logs")
@RequiredArgsConstructor
public class OperationLogController {
    
    private final OperationLogService operationLogService;
    
    @GetMapping
    @PreAuthorize("hasAuthority('log:list')")
    public ResponseEntity<Page<OperationLog>> getLogs(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long userId,
            @RequestParam(required = false) String operationType,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime startTime,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime endTime) {
        
        LambdaQueryWrapper<OperationLog> queryWrapper = new LambdaQueryWrapper<>();
        if (userId != null) {
            queryWrapper.eq(OperationLog::getUserId, userId);
        }
        if (operationType != null && !operationType.isEmpty()) {
            queryWrapper.eq(OperationLog::getOperationType, operationType);
        }
        if (startTime != null) {
            queryWrapper.ge(OperationLog::getCreateTime, startTime);
        }
        if (endTime != null) {
            queryWrapper.le(OperationLog::getCreateTime, endTime);
        }
        
        queryWrapper.orderByDesc(OperationLog::getCreateTime);
        
        Page<OperationLog> page = operationLogService.page(new Page<>(current, size), queryWrapper);
        return ResponseEntity.ok(page);
    }
    
    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('log:view')")
    public ResponseEntity<OperationLog> getLogById(@PathVariable Long id) {
        OperationLog log = operationLogService.getById(id);
        if (log == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(log);
    }
} 